<template>
<div class="container">

        <div
            ref="container"
            class="content"
            @drop="handleDrop"
            @dragover="handleDragOver"
            @mousedown="handleMouseDown"
            @mouseup="deselectCurComponent"
            @dblclick="handleDblClick"
        >
          <!-- <Editor></Editor> -->
           <DrawCanvasRun></DrawCanvasRun>
           
        </div>
        <StatusBar class="status-bar"></StatusBar>

        <!-- <div class="status-bar">
          <p>这是状态栏</p>
        </div> -->

  </div>
</template>

<script>
// @ is an alias to /src

import ComponentList from "@/components/ComponentList";
import Editor from "@/components/Editor/DrawCanvas"
import DrawCanvasRun from "./DrawCanvasRun.vue";
import {mapState} from "vuex";
import {listenGlobalKeyDown} from "@/utils/shortcutKey";
import {setDefaultcomponentData} from "@/store/snapshot";
import {deepCopy} from "@/utils/utils";
import componentList from "@/custom-component/component-list";
import generateID from "@/utils/generateID";
import {changeComponentSizeWithScale} from "@/utils/changeComponentsSizeWithScale";
import Hg3000Link from "@/custom-component/common/Hg3000Link.vue"
import StatusBar from "./statusbar/StatusBar.vue";
import eventBus from '@/utils/eventBus'
import request from "@/utils/drawutils/request";

export default {
  name: 'DrawHomeView',
  components: {
     Editor,  Hg3000Link, StatusBar, DrawCanvasRun
  },
  data() {
    return {
      activeName: 'attr',
      reSelectAnimateIndex: undefined,
      localStorageName: "drawedt",
    }
  },
  computed: mapState([
    'componentData',
    'curComponent',
    'isClickComponent',
    'canvasStyleData',
    'editor',
    'iSelectShapeIndex',
  ]),

  created() {
    // 全局监听按键事件
    listenGlobalKeyDown()
    eventBus.$on('eventScrollToTop', this.scrollToTop)
  },

  mounted() {
      window.addEventListener('storage', this.watchStorage )
      console.log( "query name", this.$route.query.name )

      let vara = { drawstr: "",  projectid: "3f61812fb43942b4adb71f51e002a471"}
      localStorage.setItem(  "edtaaa", JSON.stringify( vara ) )    

      if( this.$route.query.name )
        this.localStorageName = this.$route.query.name

      if( this.$route.query.projectid ){
        this.$store.commit('setProjectId',  this.$route.query.projectid )  
      }
      
      this.$store.commit('loadDrwFromLocalStorage', this.localStorageName )

      if(  this.localStorageName.startsWith("view") )
        localStorage.removeItem( this.localStorageName )

      this.$store.dispatch('createSocket', true )
      this.$store.commit('setModeRun', true )   //置运行标志

      //使用完后删除这个条目的另一种方法
      // var array = []
      // for (let i = 0; i < localStorage.length; i++) {
      //     const key = localStorage.key(i);      // 获取键名
      //     const value = localStorage.getItem(key);  // 获取键对应的值
      //     //console.log(`${key}: ${value}`);
      //     if( key.startsWith("view") )
      //       array.push( key )      
      // }
      
      // array.forEach(element => {
      //   localStorage.removeItem( element )
      // });

      //查询历史报警信息
      // request.get( "/savedb/getalarm" ).then( res=>{
      //   this.$store.commit('addAlarmArray', res.data  )  
      // })

  },

  unmounted() {
    window.removeEventListener('storage', this.watchStorage)
  },

  methods: {
    restore() {
      if (localStorage.getItem('drawedt')) {
        this.loadDrw(  localStorage.getItem('drwedt')  )
      }
    },

    watchStorage( event ){
      // console.log( "listen are" )
        if (event.key ===  this.localStorageName ) {
          let drawobj = JSON.parse( event.newValue )
          if( drawobj && drawobj.drawstr )
            this.loadDrw( drawobj.drawstr )

          // this.loadDrw( event.newValue )
          console.log('Received message:', event.newValue);
        }
    },

    loadDrw( content ){
      this.$store.commit('loaddrw', content )
      this.$store.commit('clearInit', { componentData: this.componentData } )

      // var webdrw = JSON.parse( content )

      // this.$store.commit('setCurComponent', { component: null, index: null })
      // this.$store.commit('setComponentData', webdrw.canvasData)
      // this.$store.commit('aceSetCanvasData', webdrw.canvasStyle)
      // this.$store.commit('recordSnapshot')
    },

    createShape( e ) {
      console.log("create shape ")
      // e.preventDefault()
      e.stopPropagation()
      if( this.iSelectShapeIndex < 0 )
        return

      const rectInfo = this.editor.getBoundingClientRect()
      
        const component = deepCopy(componentList[this.iSelectShapeIndex])
        // console.log( "component", component )
        component.style.top = e.clientY - rectInfo.y
        //格式化这个top值
        component.style.top = Number( component.style.top.toFixed(0) )

        //格式化这个left值
        component.style.left = e.clientX - rectInfo.x
        component.style.left = Number( component.style.left.toFixed(0) )

        // console.log('pos', component.style.left, component.style.top)

        component.id = generateID()

        // 根据画面比例修改组件样式比例 https://github.com/woai3c/visual-drag-demo/issues/91
        changeComponentSizeWithScale(component)

        this.$store.commit('addComponent', { component })
        this.$store.commit('recordSnapshot')

    },

    handleDrop(e) {
      console.log("drop")
      e.preventDefault()
      // e.stopPropagation()

      const index = e.dataTransfer.getData('index')
      console.log( "drop index:  ", index )
      const rectInfo = this.editor.getBoundingClientRect()
      if (index) {
        const component = deepCopy(componentList[index])
        // console.log( "component", component )
        component.style.top = e.clientY - rectInfo.y
        //格式化这个top值
        component.style.top = Number( component.style.top.toFixed(0) )

        //格式化这个left值
        component.style.left = e.clientX - rectInfo.x
        component.style.left = Number( component.style.left.toFixed(0) )

        // console.log('pos', component.style.left, component.style.top)

        component.id = generateID()

        // 根据画面比例修改组件样式比例 https://github.com/woai3c/visual-drag-demo/issues/91
        changeComponentSizeWithScale(component)

        this.$store.commit('addComponent', { component })
        this.$store.commit('recordSnapshot')
      }
      console.log('drop')
    },

    handleDragOver(e) {
      console.log('over')
      e.preventDefault()
      e.dataTransfer.dropEffect = 'copy'
    },

    //画布点中的处理工作  在选择状态下处理
    handleMouseDown(e) {
      if (e.button == 2 ) {   //右键在这里不执行功能，这里只处理左键的点击
        return 
      }
      //不建立图形对象
      if( this.iSelectShapeIndex < 0 ){    
        e.stopPropagation()
        this.$store.commit('setClickComponentStatus', false)
        this.$store.commit('setInEditorStatus', true)
        console.log('mousedown')
      }
      else{  //建立图形对象
          this.createShape( e )
      }

    },

    //双击后使用选择功能
    handleDblClick(  ){
      //this.$store.commit( "setSelectShapeIndex", -1 )
    },

    deselectCurComponent(e) {
      if (!this.isClickComponent) {
        this.$store.commit('setCurComponent', { component: null, index: null })
      }

      // 0 左击 1 滚轮 2 右击
      if (e.button != 2) {
        this.$store.commit('hideContextMenu')
      }
    },
    scrollToTop(  ){
      this.$refs.container.scrollTop = 0;
      // console.log( "scroll to top" )
    }

  },
}
</script>

<style  lang="scss">
.home {
    height: 100vh;
    background: #fff;
    main {
      height: calc(100% - 3vh);
      position: relative;

      .center {
        margin-left: 0vh;
        margin-right: 0vh;
        background: #f5f5f5;
        // height: calc(100% - 1vh);
        height: 100vh;
        overflow: auto;
        padding: 0px;

        .content {
          width: 100%;
          height: 100%;
          overflow: auto;
        }
      }

    }
}

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html, body, .container {
  height: 100%;
  margin: 0;
}

.container {
  display: flex;
  flex-direction: column;
  height: 100vh; /* 使用视窗高度 */
}

.content {
  flex-grow: 1; /* 主内容部分占据剩余空间 */
  padding: 0px;
  background-color: #f0f0f0;
  overflow-y: auto;
}

.status-bar {
  
  background-color: #333;
  color: white;
  text-align: center;
  line-height: 40px; /* 垂直居中文本 */
}

</style>

